package ch.pizzapp.kurier;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import ch.pizzapp.kurier.client.InfoClient;
import ch.pizzapp.kurier.data.InfoData;
import ch.pizzapp.kurier.data.ResponceData;
import ch.pizzapp.kurier.dto.InfoDto;

import com.bugsense.trace.BugSenseHandler;
import com.google.android.gcm.GCMRegistrar;

@EActivity(R.layout.activity_main)
public class MainActivity extends ActionBarActivity {

	@Bean
	InfoDto infoDto;
	@RestService
	InfoClient infoClient;

	@ViewById(R.id.address1)
	TextView address1tv;

	@ViewById(R.id.opentime)
	TextView opentime;

	@ViewById(R.id.tel)
	TextView tel;

	@ViewById(R.id.textViewCompany)
	TextView textViewCompany;

	@ViewById(R.id.data)
	protected RelativeLayout data;

	@ViewById(R.id.login_status)
	protected LinearLayout mLoginStatusView;
	@ViewById(R.id.loginButton)
	Button loginButton;

	ResponceData responceDataParce;

	// Connection detector
	ConnectionDetector cd;

	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();

	// Asyntask
	AsyncTask<Void, Void, Void> mRegisterTask;

	@AfterViews
	void iniUi() {

		BugSenseHandler
				.initAndStartSession(MainActivity.this, Constants.APIKEY);
		BugSenseHandler.startSession(MainActivity.this);
		LoginFragment fragment = new LoginFragment();

		getSupportFragmentManager().beginTransaction()
				.replace(R.id.container, fragment).commit();

		// gcm

		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				Constants.DISPLAY_MESSAGE_ACTION));

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			GCMRegistrar.register(this, Constants.SENDER_ID);
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				// Toast.makeText(getApplicationContext(),
				// "Already registered with GCM", Toast.LENGTH_LONG)
				// .show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						ServerUtilities.register(context, "android",
								"shanukagayashan@gmail.com", regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}

	}

	/**
	 * Receiving push messages
	 * */
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(
					Constants.EXTRA_MESSAGE);
			// Waking up mobile if it is sleeping
			WakeLocker.acquire(getApplicationContext());

			/**
			 * Take appropriate action on this message depending upon your app
			 * requirement For now i am just displaying it on the screen
			 * */

			// // Showing received message
			// lblMessage.append(newMessage + "\n");
			// Toast.makeText(getApplicationContext(),
			// "New Message: " + newMessage, Toast.LENGTH_LONG).show();

			// Releasing wake lock
			WakeLocker.release();
		}
	};

	@Override
	protected void onDestroy() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true);
		}
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
		} catch (Exception e) {
			Log.e("UnRegister Receiver Error", "> " + e.getMessage());
		}
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		System.out.println("on crete");
		getInfo();

	}

	//Map<String, Integer> datesMap = new HashMap<String, Integer>();

	@Background
	void getInfo() {

//		datesMap.put("Mon", 1);
//		datesMap.put("Tue", 2);
//		datesMap.put("Wed", 3);
//		datesMap.put("Thu", 4);
//		datesMap.put("Fri", 5);
//		datesMap.put("Sat", 6);
//		datesMap.put("Sun", 7);

		//SimpleDateFormat dateFormat = new SimpleDateFormat("EEE");
		Date date = new Date();

		SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
		// Date date = new Date();

		infoDto.setDate(sm.format(date));
		
		Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.DAY_OF_WEEK) == 1)
        {
            infoDto.setDay("7");
        } else
        {
            infoDto.setDay(String.valueOf(-1 + calendar.get(Calendar.DAY_OF_WEEK)));
        }
		infoDto.setType("11");

		new ReachabilityTest(MainActivity.this,
				new ReachabilityTest.Callback() {

					@Override
					public void onReachabilityTestPassed() {

						try {
							setInfor(infoClient.getInfo(infoDto
									.getMultiValuedMap()));
						} catch (Exception e) {

							System.err.println(e);
						}
					}

					@Override
					public void onReachabilityTestFailed() {
						showProgress(false);
						showMessge("Not connected ");
					}
				});
	}

	@UiThread
	void setInfor(final ResponceData responceData) {

		showProgress(false);

		InfoData infoData = responceData.getResponse();

		loginButton.setEnabled(true);

		responceDataParce = responceData;

		if (infoData != null) {

			String address1 = infoData.getAddress1() + " "
					+ infoData.getAddress2() + ", " + infoData.getZip() + ", "
					+ infoData.getCity();

			address1tv.setText("" + address1);
			opentime.setText("" + infoData.getOpentime());

			tel.setText("" + infoData.getTel());

		}

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
	}

	@Click({ R.id.loginButton, R.id.tel, R.id.textViewCompany })
	void onClick(View view) {
		switch (view.getId()) {
		case R.id.loginButton:
			openDialog();
			break;

		case R.id.tel:
			try {
				Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent
						.setData(Uri.parse("tel:" + tel.getText().toString()));
				startActivity(callIntent);
			} catch (ActivityNotFoundException activityException) {
				Log.e(" dialer", "Call failed", activityException);
			}
			break;

		case R.id.textViewCompany:
			String url = Constants.WEB_URL;
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(url));
			startActivity(i);
			break;
		default:
			break;

		}
	}

	private void openDialog() {
		final Dialog dialog = new Dialog(MainActivity.this);
		dialog.setTitle("login");
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.login_dialog);
		dialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
		dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

		dialog.getWindow().setGravity(Gravity.BOTTOM);
		Button btnDismiss = (Button) dialog.getWindow().findViewById(
				R.id.cancelButton);

		Button loginButton = (Button) dialog.getWindow().findViewById(
				R.id.loginButton);

		Button registerButton = (Button) dialog.getWindow().findViewById(
				R.id.registerButton);

		registerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(MainActivity.this,
						SignUpActivity_.class);
				
				if (responceDataParce != null) {
					intent.putExtra("ResponceData", responceDataParce);

				}

				startActivity(intent);
				dialog.dismiss();
				overridePendingTransition(R.anim.open_next, R.anim.close_main);

			}
		});

		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(MainActivity.this,
						LoginActivity_.class);

				if (responceDataParce != null) {
					intent.putExtra("ResponceData", responceDataParce);

				}

				startActivity(intent);
				dialog.dismiss();
				overridePendingTransition(R.anim.open_next, R.anim.close_main);

			}
		});

		Button withoutloginButton = (Button) dialog.getWindow().findViewById(
				R.id.withoutloginButton);

		withoutloginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this,
						PlacesActivity_.class);
				if (responceDataParce != null) {
					intent.putExtra("ResponceData", responceDataParce);
				}
				startActivity(intent);

				overridePendingTransition(R.anim.open_next, R.anim.close_main);

				dialog.dismiss();

			}
		});

		btnDismiss.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	@UiThread
	void showProgress(final boolean show) {
		mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
		data.setVisibility(show ? View.GONE : View.VISIBLE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu items for use in the action bar
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle presses on the action bar items
		switch (item.getItemId()) {
		case R.id.menu_item_share:
			// openSearch();

			NotificationFragment fragment = new NotificationFragment_();

			final FragmentTransaction transaction = getSupportFragmentManager()
					.beginTransaction();
			transaction.add(R.id.container, fragment);
			transaction.addToBackStack(null);
			transaction.commit();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
